package org.seven.jrdp.biz.t.service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.seven.jrdp.biz.t.mapper.TFxdMapper;
import org.seven.jrdp.biz.t.mapper.TRkdMapper;
import org.seven.jrdp.biz.t.model.TFxd;
import org.seven.jrdp.biz.t.model.TRkd;
import org.seven.jrdp.biz.t.plugin.ys.YsPlugin;
import org.seven.jrdp.commons.exception.BizException;
import org.seven.jrdp.commons.mybatis.model.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class TFxdService {
	@Autowired
	private TFxdMapper tFxdMapper;
	@Autowired
	private TRkdMapper tRkdMapper;

	@Transactional(readOnly = true)
	public PageInfo<Map<String, Object>> find(Map<String, Object> map, PageRequest pageRequest) {
		PageHelper.startPage(pageRequest.getPage(), pageRequest.getRows());
		List<Map<String, Object>> list = tFxdMapper.find(map);
		for (Map<String, Object> fxd : list) {
			List<Map<String, Object>> mx = tFxdMapper.findMx((String) fxd.get("cpbh"));
			for (Map<String, Object> ys : mx) {
				YsPlugin.check(ys);
			}
			fxd.put("mx", mx);
		}
		return new PageInfo<Map<String, Object>>(list);
	}

	@Transactional(readOnly = true)
	public List<Map<String, Object>> findRkfx(String cpbh) {
		return tFxdMapper.findRkfx(cpbh);
	}

	@Transactional(readOnly = true)
	public List<Map<String, Object>> findCkfx(String cpbh) {
		return tFxdMapper.findCkfx(cpbh);
	}

	@Transactional
	public void saveRkfx(List<TFxd> list) {
		for (int i = 0; i < list.size(); i++) {
			TFxd tFxd = list.get(i);
			try {
				Double.valueOf(tFxd.getRkfx());
			} catch (Exception e) {
				throw new BizException(String.format("第%d行，入库分析格式错误，请重新输入", i + 1));
			}
			if (tFxdMapper.selectByPrimaryKey(tFxd) == null) {
				tFxdMapper.insertSelective(tFxd);
			} else {
				tFxdMapper.updateByPrimaryKeySelective(tFxd);
			}
		}
	}

	@Transactional
	public void saveCkfx(TRkd tRkd, List<TFxd> list) {
		for (int i = 0; i < list.size(); i++) {
			TFxd tFxd = list.get(i);
			try {
				double rkfx = Double.valueOf(tFxd.getRkfx());
				double ckfx = Double.valueOf(tFxd.getCkfx());
				BigDecimal ysnr = new BigDecimal(rkfx - ckfx);
				int index = tFxd.getRkfx().indexOf(".");
				int len = 0;
				if (index > 0) {
					len = tFxd.getRkfx().substring(index).length() - 1;
				}
				tFxd.setPcfx(ysnr.setScale(len, BigDecimal.ROUND_HALF_UP).toString());
			} catch (Exception e) {
				throw new BizException(String.format("第%d行，出库分析格式错误，请重新输入", i + 1));
			}
			tFxdMapper.updateByPrimaryKeySelective(tFxd);
		}
		tRkdMapper.updateByPrimaryKeySelective(tRkd);
	}
}